<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends BaseController {
    public function __construct() {
        parent::__construct();

        // 移动端初始化方法
        $this->wx_init();
        
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
    }

    /*
     * 个人中心页面
    */
    public function index() {
        $this->htmlTitle = '个人中心';
        // // // 任课班级，截取前两个班级
        // if(isset($this->user['classNameStr']) && $this->user['classNameStr']) {
        //     $arr = explode('、', $this->user['classNameStr']);
        //     if(count($arr) > 2) {
        //         $newArr = array_slice($arr, 0, 2);
        //         $this->user['classNameStr'] = implode('、', $newArr) . '...';
        //     }
        // }
        // 获取任课班级列表
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // 教师权限
            // $teacherClassArr = $this->get_classes_by_teacher_id(true);
            // 任课班级那里，也显示班主任的班级
            $teacherClassArr = $this->get_classes_by_teacher_id(false, false);
            if($teacherClassArr) {
                if(count($teacherClassArr) === 1) {
                    $classNameStr = $teacherClassArr[0]['class_name'];
                } else {
                    $classNameStr = $teacherClassArr[0]['class_name'] . '、' . $teacherClassArr[1]['class_name'];
                    if(count($teacherClassArr) > 2) {
                        $classNameStr .= '...';
                    }
                }
                $this->user['classNameStr'] = $classNameStr;
            }
            $this->teacherClassArr = $teacherClassArr;
            // 管理员权限，获取学校名称
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $this->schoolName = $schoolInfo['school_name'];
            $isMaster = false;
            $brandInfo = array();
            $isGradeAdmin = false;
            $isSchoolAdmin = false;
            $gradeNameStr = '';
             // 获取班主任对应的班级列表
             $coachParams['teacherId'] = $this->user['id'];
             $coachParams['coachType'] = COACH_TYPE_MASTER; 
             $this->load->model('staffModel');
             $masterCoachList = $this->staffModel->get_coach_list($coachParams);
             if($masterCoachList) {
                 $masterClassIdArr = array();
                 // 获取任教班主任班级列表
                 foreach($masterCoachList as $coach) {
                    $idArr = explode(',', $coach['class_ids']);
                    foreach($idArr as $id) {
                       if(!in_array($id, $masterClassIdArr)) {
                           array_push($masterClassIdArr, $id);
                       }
                    }
                }
                // 判断是否已删除
                foreach($masterClassIdArr as $masterClassId) {
                    $classInfo = $this->classesModel->get_class_info($masterClassId);
                    // 过滤年级已删除
                    if($classInfo) {
                        $gradeId = $classInfo['grade_id'];
                        $gradeInfo = $this->classesModel->get_grade_info($gradeId);
                    }
                    if($classInfo && $classInfo['is_delete'] == 0 && isset($gradeInfo) && $gradeInfo['is_delete'] == 0) {
                        $isMaster = true;
                        // 判断班主任对应的班级是否存在班牌
                        $brandInfo = $this->classesModel->get_brand_info_by_class($classInfo['id']);
                        break;
                    }
                }
             }

            // 获取年级管理员对应的年级列表
            $coachParams['teacherId'] = $this->user['id'];
            $coachParams['coachType'] = COACH_TYPE_GRADE_ADMIN; 
            $gradeCoachList = $this->staffModel->get_coach_list($coachParams);
            if($gradeCoachList) {
                $gradeIdArr = array();
                // 获取管理年级列表
                foreach($gradeCoachList as $coach) {
                    if(!in_array($coach['grade_id'], $gradeIdArr)) {
                        array_push($gradeIdArr, $coach['grade_id']);
                    }
                }
                // 判断是否已删除
                foreach($gradeIdArr as $gradeId) {
                    $gradeInfo = $this->classesModel->get_grade_info($gradeId);
                    // 过滤年级已删除
                    $gradeNameArr = array();
                    if($gradeInfo && $gradeInfo['is_delete'] == 0 ) {
                        $isGradeAdmin = true;
                        array_push($gradeNameArr, $gradeInfo['grade_name']);
                    }
                    $gradeNameStr = implode('、', $gradeNameArr);
                }
            }

            // 获取学校管理员对应的年级列表
            $coachParams['teacherId'] = $this->user['id'];
            $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN; 
            $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
            if($schoolAdminCoachList) {
                $isSchoolAdmin = true;
            }

             // 管理员可以上传全校学生人脸
             if($this->user['user_type'] == USER_TYPE_SCHOOL) {
                 $isMaster = true;
             }
             //  是否班主任
             $this->isMaster = $isMaster;
             // 班主任所在班级班牌
             $this->brandInfo = $brandInfo;
             // 是否年级管理员
             $this->isGradeAdmin = $isGradeAdmin;
             $this->gradeNameStr = $gradeNameStr;
             // 是否学校管理员
             $this->isSchoolAdmin = $isSchoolAdmin;
        }
     
        // // echo '<pre>';var_export($brandInfo);exit;
        // if(!isset($this->wxSession['qywx'])) {
        //     // 获取jssdk参数
        //     $this->load->library('wechat');
        //     $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        //     $this->dataJssdk = $this->wechat->jssdk_data($url);
        // } else {
        //     // 获取jssdk参数
        //     $this->load->library('qyWechat');
        //     $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        //     $this->dataJssdk = $this->qywechat->jssdk_data($url);
        // }

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
       
        // echo '<pre>';var_export($this->user);exit;

        // 学校是否开通闸机功能
        $hasGate = false;
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
            $moduleSetArr = explode(',', $schoolInfo['school_module_set']);
            // 获取闸机权限id
            $this->load->model('accountModel');
            $menuInfo = $this->accountModel->get_menu_info_by_name('闸机管理');
            if($menuInfo) {
                if(in_array($menuInfo['id'], $moduleSetArr)) {
                    $hasGate = true;
                }
            }
        }
        $this->hasGate = $hasGate;

        // 学校是否关闭人脸识别
        $schoolInfo = $this->schoolModel->get_school_info($this->user['school_id']);
        $this->schoolFaceFetect = $schoolInfo['school_face_detect'];

        // 学校是否开启教师考勤
        $this->enableTeacherSign = $schoolInfo['enable_teacher_sign'];

        // $this->aa = json_encode($this->session->userdata['wx'], JSON_UNESCAPED_UNICODE);
        // echo '<pre>';var_export($this->aa);exit;
        // echo '<pre>';var_export($this->session->userdata);exit;


        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/center');
    }

   
    public function clear_session() {
        $this->session->set_userdata('wx', array());
        echo '清除缓存成功';exit;
    }

    public function test() {
        echo '<pre>';var_export(session_id());exit;
        echo '<pre>';var_export($this->session->userdata);exit;
    }

    // 保存电话操作
    public function save_mobile_action() {
        $userId = $this->post('user_id');
        $bindUserType = $this->post('bind_user_type');
        $mobile = trim($this->post('mobile'));
        if(empty($mobile) || !str_is_mobile($mobile)) {
            throw new Exception("请填写正确的手机号码");
        }
        // 入库
        $data = array(
            'mobile' => $mobile,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $userId);
        if($bindUserType == BIND_TYPE_STUDENT) {
            $this->db->update(SchoolModel::$schoolStudentTable, $data);
        } else {
            $this->db->update(SchoolModel::$schoolUserTable, $data);
        }
        exit(json('修改成功', true));
    }

    // 保存密码操作
    public function save_password_action() {
        $userId = $this->post('user_id');

        // // 原来的正确密码hash
        // $passwordHash = $this->post('password_hash');
        // $passwordOld = trim($this->post('password_old'));
        // $passwordNew = trim($this->post('password_new'));
        // $passwordConfirm = trim($this->post('password_confirm'));
        // if(empty($passwordOld) || empty($passwordNew) || empty($passwordConfirm)) {
        //     throw new Exception("密码不能为空");
        // }
        // if(!password_verify($passwordOld, $passwordHash)) {
        //     throw new Exception('旧密码不正确');
        // }
        // if(!str_is_password($passwordNew)) {
        //     throw new Exception('新密码格式不正确');
        // }
        // if($passwordNew !== $passwordConfirm) {
        //     throw new Exception('两次密码输入不同');
        // }

        $password = trim($this->post('password'));
        if(empty($password)) {
            throw new Exception("密码不能为空");
        }
        if(!str_is_password($password)) {
            throw new Exception('密码格式不正确');
        }
        // 入库
        $data = array(
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $userId);
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            $this->db->update(SchoolModel::$schoolStudentTable, $data);
        } else {
            $this->db->update(SchoolModel::$schoolUserTable, $data);
        }
        exit(json('修改成功', true));
    }

    // 保存班牌密码操作
    public function save_brand_password_action() {
        $brandId = $this->post('id');
        $brandPassword = trim($this->post('brand_password'));
        if(empty($brandPassword)) {
            throw new Exception("密码不能为空");
        }
        if(!str_is_password($brandPassword)) {
            throw new Exception('密码格式不正确');
        }
        // 入库
        $data = array(
            'brand_password' => $brandPassword,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $brandId);
        $this->db->update(ClassesModel::$brandTable, $data);

        exit(json('修改成功', true));
    }

    // 保存头像操作
    public function save_headimg_action() {
        $userId = $this->post('user_id');
        $bindUserType = $this->post('bind_user_type');
        $headimgurl = trim($this->post('headimgurl'));

        // 入库
        $data = array(
            'headimgurl' => $headimgurl,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $userId);
        if($bindUserType == BIND_TYPE_STUDENT) {
            $this->db->update(SchoolModel::$schoolStudentTable, $data);
        } else {
            $this->db->update(SchoolModel::$schoolUserTable, $data);
        }
        exit(json('', true));
    }

    // 解绑账号操作
    public function unbind_card_action() {
        // 获取当前微信账号
        $openid = $this->wxSession['openid'];
        $wxUser = $this->wxUserModel->get_wx_user_by_openid($openid);
        // 获取当前绑定关系
        $userBindInfo = $this->wxUserModel->get_bind_user_info($wxUser['id'], $this->user['id'], $this->bindUserType);
        // 删除绑定关系
        $this->db->update(WxUserModel::$wxUserBindTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ),  array(
            'id' => $userBindInfo['id']
        ));
        // 清除user和usertype的session
        $this->session->set_userdata('wx', array(
            'openid' => $this->wxSession['openid']
        ));

        exit(json('解绑成功', true));
    }

    /*
     * 人脸图片页面
    */
    public function face() {
        $this->htmlTitle = '人脸图片';

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/face');
    }

    // 保存人脸图片
    public function save_face_action() {
        $studentId = $this->post('student_id');
        $faceimg = trim($this->post('faceimg'));
        $oldStudentInfo = $this->schoolModel->get_student_info($studentId);

        // 删除人脸不用检测
        if($faceimg && ENV == 'production') {
            // 检测人脸
            $this->load->library('aliapi');
            $ret = $this->aliapi->detect_face($faceimg);
            // throw new Exception($ret['LandmarkCount']);
            if($ret['success'] == false) {
                throw new Exception($ret['msg']);
            }
            if($ret['faceCount'] == 0) {
                throw new Exception('上传错误，没有检测到人脸');  
            }
            if($ret['faceCount'] > 1) {
                throw new Exception('上传错误，人脸个数过多');  
            }
            // 判断角度
            foreach($ret['poseList'] as $item) {
                if($item > 10 || $item < -10) {
                    throw new Exception('上传错误，请正对镜头'); 
                }
            }
        }

        // 入库
        $data = array(
            'face_image' => $faceimg,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$schoolStudentTable, $data, array(
            'id' => $studentId
        ));
        // 发送socket
        $this->load->library('socket');
        // $classId = $this->user['class_id'];
        $studentInfo = $this->schoolModel->get_student_info($studentId);
        $brandInfo = $this->classesModel->get_brand_info_by_class($studentInfo['class_id']);
        if($brandInfo) {
            $brandId = $brandInfo['id'];
            $this->socket->send_face_image_update($brandId, $studentId, $faceimg);
        }
        $msg = $faceimg ? '上传成功' : '删除成功';

        // 插入闸机任务
        // $gateParams['schoolId'] = $studentInfo['school_id'];
        // $gateParams['campusId'] = $studentInfo['campus_id'];
        // $gateParams['isDelete'] = 0;
        // $gateList = $this->schoolModel->get_gate_list($gateParams);
        // if($gateList) {
        //     $insertTaskBatch = array();
        //     if($faceimg) {
        //         if($oldStudentInfo['face_image'] || $oldStudentInfo['realcard']) {
        //             // 修改
        //             $taskType = GATE_TASK_TYPE_UPDATE;
        //         } else {
        //             // 新增
        //             $taskType = GATE_TASK_TYPE_ADD;
        //         }
        //     } else {
        //         // 删除人脸
        //         if($oldStudentInfo['realcard']) {
        //             // 修改
        //             $taskType = GATE_TASK_TYPE_UPDATE;
        //         } else {
        //             // 删除
        //             $taskType = GATE_TASK_TYPE_DELETE;
        //         }
        //     }
        //     foreach($gateList as $gate) {
        //         $gateFaceimg = $faceimg ? $faceimg : $studentInfo['face_image'];
        //         $arr = $this->schoolModel->format_gate_task($studentInfo['school_id'], $studentInfo['campus_id'], $gate['id'], $gate['device_sn'], $studentInfo['id'],
        //             $studentInfo['realname'], $gateFaceimg, GATE_USER_TYPE_STUDENT, $taskType, GATE_TASK_STATE_NEW, $studentInfo['realcard']);
        //         array_push($insertTaskBatch, $arr);
        //     }
        //     if($insertTaskBatch) {
        //         // 插入闸机任务
        //         $this->schoolModel->insert_gate_task_batch($insertTaskBatch);
        //     }
        // }
        if($faceimg) {
            if($oldStudentInfo['face_image'] || $oldStudentInfo['realcard']) {
                // 修改
                $gateTaskType = GATE_TASK_TYPE_UPDATE;
            } else {
                // 新增
                $gateTaskType = GATE_TASK_TYPE_ADD;
            }
        } else {
            // 删除人脸
            if($oldStudentInfo['realcard']) {
                // 修改
                $gateTaskType = GATE_TASK_TYPE_UPDATE;
            } else {
                // 删除
                $gateTaskType = GATE_TASK_TYPE_DELETE;
            }
        }
        $studentInfo['face_image'] = $faceimg ? $faceimg : $studentInfo['face_image'];
        // $this->load->model('gateModel');
        // $this->gateModel->add_gate_task($studentInfo['school_id'], $studentInfo['campus_id'], $gateTaskType, $studentInfo, GATE_USER_TYPE_STUDENT);

        // 插入一体机任务
        $this->load->model('aioModel');
        $aioParams['schoolId'] = $studentInfo['school_id'];
        $aioParams['campusId'] = $studentInfo['campus_id'];
        $aioParams['isDelete'] = 0;
        $aioList = $this->aioModel->get_aio_list($aioParams);
        if($aioList) {
            $insertTaskBatch = array();
            if($faceimg) {
                if($oldStudentInfo['face_image']) {
                    // 修改
                    $taskType = AIO_TASK_TYPE_UPDATE;
                } else {
                    // 新增
                    $taskType = AIO_TASK_TYPE_ADD;
                }
            } else {
                // 删除
                $taskType = AIO_TASK_TYPE_DELETE;
            }
            foreach($aioList as $aio) {
                array_push($insertTaskBatch, array(
                    'school_id' => $studentInfo['school_id'],
                    'campus_id' => $studentInfo['campus_id'],
                    'aio_id' => $aio['id'],
                    'facesluice_id' => $aio['facesluice_id'],
                    'user_id' => $studentInfo['id'],
                    'user_name' => $studentInfo['realname'],
                    'user_face_image' => $faceimg ? $faceimg : $studentInfo['face_image'],
                    'user_type' => AIO_USER_TYPE_STUDENT,
                    'task_type' => $taskType,
                    'task_state' => AIO_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
            }
        }

        exit(json($msg, true));
    }

    // 学生人脸班级列表页面
    public function student_face_class() {
        $this->htmlTitle = '学生人脸录入';
        
        // 只获取行政班
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
    
        // 管理员可以上传全校学生人脸
        if($this->user['user_type'] == USER_TYPE_SCHOOL) {
            $classParams['isDelete'] = 0;
            $classParams['schoolId'] = $this->user['school_id'];
            $classArr = $this->classesModel->get_class_list($classParams);
            foreach($classArr as $key => $class) {
                // 获取某班级所有学生
                $stuParams['schoolId'] = $this->user['school_id'];
                $stuParams['classId'] = $class['id'];
                $stuParams['isDelete'] = 0;
                $stuParams['getRowNumber'] = 1;
                $classArr[$key]['studentCount'] = $this->schoolModel->get_student_list($stuParams);
            }
            $this->classArr = $classArr;
        } else {
        // 获取班主任对应的班级列表
        $coachParams['teacherId'] = $this->user['id'];
        $coachParams['coachType'] = COACH_TYPE_MASTER; 
        $this->load->model('staffModel');
        $coachList = $this->staffModel->get_coach_list($coachParams);
            if($coachList) {
                $masterClassIdArr = array();
                // 获取任教班主任班级列表
                foreach($coachList as $coach) {
                $idArr = explode(',', $coach['class_ids']);
                foreach($idArr as $id) {
                    if(!in_array($id, $masterClassIdArr)) {
                        array_push($masterClassIdArr, $id);
                    }
                }
                }
                $classParams['isDelete'] = 0;
                $classParams['classId'] = implode(',', $masterClassIdArr);
                $classArr = $this->classesModel->get_class_list($classParams);
                foreach($classArr as $key => $class) {
                    // 获取某班级所有学生
                    $stuParams['schoolId'] = $this->user['school_id'];
                    $stuParams['classId'] = $class['id'];
                    $stuParams['isDelete'] = 0;
                    $stuParams['getRowNumber'] = 1;
                    $classArr[$key]['studentCount'] = $this->schoolModel->get_student_list($stuParams);
                }
                $this->classArr = $classArr;
                // echo'<pre>';var_export($classArr);exit;
            }
        }
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/student_face_class');
    }

    // 班级学生人脸页面
    public function student_face($classId) {
        $this->htmlTitle = '学生人脸录入';

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);

        $this->classInfo = $this->classesModel->get_class_info($classId);
        // 获取班级所有学生
        $stuParams['schoolId'] = $this->user['school_id'];
        $stuParams['classId'] = $classId;
        $stuParams['isDelete'] = 0;
        $studentArr = $this->schoolModel->get_student_list($stuParams);
        if($studentArr) {
            foreach($studentArr as $k => $student) {
                // 获取首字母
                $studentArr[$k]['realnameFirstChar'] = getFirstChar($student['realname']);
            }
            // 按姓名首字母排序
            $timeKey =  array_column($studentArr, 'realnameFirstChar');
            array_multisort($timeKey, SORT_ASC, $studentArr);
        }
        $readyStudentArr = $unreadyStudentArr = array();
        foreach($studentArr as $student) {
            if($student['face_image']) {
                // 已录入人脸学生列表
                array_push($readyStudentArr, $student);
            } else {
                // 未录入人脸学生列表
                array_push($unreadyStudentArr, $student);
            }
        }
        $this->studentArr = $studentArr;
        $this->readyStudentArr = $readyStudentArr;
        $this->unreadyStudentArr = $unreadyStudentArr;
        // echo'<pre>';var_export($studentArr);exit;

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/student_face');
    }

    /*
     * 人脸图片页面
    */
    public function teacher_face() {
        $this->htmlTitle = '教师人脸图片';

        // 获取jssdk参数
        $this->load->library('wechat');
        $url = substr(BASE_URL, 0 , -1) . $_SERVER['REQUEST_URI'];
        $this->dataJssdk = $this->wechat->jssdk_data($url);
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/teacher_face');
    }

    // 保存人脸图片
    public function save_teacher_face_action() {
        $studentId = $this->post('teacher_id');
        $faceimg = trim($this->post('faceimg'));
        $oldStudentInfo = $this->schoolModel->get_teacher_info($studentId);

        // 删除人脸不用检测
        if($faceimg && ENV == 'production') {
            // 检测人脸
            $this->load->library('aliapi');
            $ret = $this->aliapi->detect_face($faceimg);
            if($ret['success'] == false) {
                throw new Exception($ret['msg']);
            }
            if($ret['faceCount'] == 0) {
                throw new Exception('上传错误，没有检测到人脸');  
            }
            if($ret['faceCount'] > 1) {
                throw new Exception('上传错误，人脸个数过多');  
            }
            // 判断角度
            foreach($ret['poseList'] as $item) {
                if($item > 10 || $item < -10) {
                    throw new Exception('上传错误，请正对镜头'); 
                }
            }
        }

        // 入库
        $data = array(
            'face_image' => $faceimg,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(SchoolModel::$schoolUserTable, $data, array(
            'id' => $studentId
        ));

        $studentInfo = $this->schoolModel->get_teacher_info($studentId);

        $msg = $faceimg ? '上传成功' : '删除成功';

        // 插入闸机任务
        $gateParams['schoolId'] = $studentInfo['school_id'];
        // 获取该学校默认校区
        $params['schoolId'] = $studentInfo['school_id'];
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusId = 0;
        foreach($campusList as $campus) {
            if($campus['campus_name'] === '默认校区') {
                $campusId = $campus['id'];
                break;
            }
        }
        // $gateParams['campusId'] = $campusId;
        // // 过滤软删除
        // $gateParams['isDelete'] = 0;
        // $gateList = $this->schoolModel->get_gate_list($gateParams);
        // // var_export($gateList);exit;
        // if($gateList) {
        //     $insertTaskBatch = array();
        //     if($faceimg) {
        //         if($oldStudentInfo['face_image'] || $oldStudentInfo['realcard']) {
        //             // 修改
        //             $taskType = GATE_TASK_TYPE_UPDATE;
        //         } else {
        //             // 新增
        //             $taskType = GATE_TASK_TYPE_ADD;
        //         }
        //     } else {
        //         // 删除人脸
        //         if($oldStudentInfo['realcard']) {
        //             // 修改
        //             $taskType = GATE_TASK_TYPE_UPDATE;
        //         } else {
        //             // 删除
        //             $taskType = GATE_TASK_TYPE_DELETE;
        //         }
        //     }
        //     foreach($gateList as $gate) {
        //         $gateFaceimg = $faceimg ? $faceimg : $studentInfo['face_image'];
        //         $arr = $this->schoolModel->format_gate_task($studentInfo['school_id'], $campusId, $gate['id'], $gate['device_sn'], $studentInfo['id'],
        //             $studentInfo['realname'], $gateFaceimg, GATE_USER_TYPE_TEACHER, $taskType, GATE_TASK_STATE_NEW, $studentInfo['realcard']);
        //         array_push($insertTaskBatch, $arr);
        //     }
        //     if($insertTaskBatch) {
        //         // 插入闸机任务
        //         $this->schoolModel->insert_gate_task_batch($insertTaskBatch);
        //     }
        // }
        if($faceimg) {
            if($oldStudentInfo['face_image'] || $oldStudentInfo['realcard']) {
                // 修改
                $gateTaskType = GATE_TASK_TYPE_UPDATE;
            } else {
                // 新增
                $gateTaskType = GATE_TASK_TYPE_ADD;
            }
        } else {
            // 删除人脸
            if($oldStudentInfo['realcard']) {
                // 修改
                $gateTaskType = GATE_TASK_TYPE_UPDATE;
            } else {
                // 删除
                $gateTaskType = GATE_TASK_TYPE_DELETE;
            }
        }
        $studentInfo['face_image'] = $faceimg ? $faceimg : $studentInfo['face_image'];
        // $this->load->model('gateModel');
        // $this->gateModel->add_gate_task($studentInfo['school_id'], $campusId, $gateTaskType, $studentInfo, GATE_USER_TYPE_TEACHER);


        exit(json($msg, true));
    }

    public function test_xinlang_face_detect() {
        //新浪云接口
        include_once(APPPATH. "libraries/Facesaegapi.php");
        $gApi = new Facesaegapi(SAE_ACCESS_KEY, SAE_SECRET_KEY);
        $imgname= 'https://resource.rongmixiao.com/2020/05/26/8ca49abfd9d3ea74d0e367c3a9f11d63.png';
        // $post_data = array();
        $post_data['img_name'] = $imgname;
        $post_data['img'] = base64_encode(file_get_contents($imgname));
        $ret = $gApi->post('/facedetection/', $post_data);
        // $retData = json_decode($ret, true);
        // echo'<pre>';
        var_export($ret);
        // if(isset($retData['error'])) {
        //     exit(json($retData['error'], false));
        // } else {
        //     exit(json("", true, $retData['data']));
        // }
    }

    public function test_ali_face_detect() {
        //阿里云接口
        // $zero = "https://resource.rongmixiao.com/2020/06/06/fea2ff6f0ba931811313e00267fc0da8.jpg";
        // $two = "https://resource.rongmixiao.com/2020/06/06/f7991b2350c58dd60ca5a2e9bbd55c1f.jpg";
        // $three = "https://resource.rongmixiao.com/2020/06/06/4514fb010d7b65e243f09b7bc9e9adf9.jpg";
        $a = 'C:\Users\Administrator\Desktop\face\1.jpg';
        $arr = array(
            'C:\Users\Administrator\Desktop\face\1.jpg',
            'C:\Users\Administrator\Desktop\face\2.jpg',
            'C:\Users\Administrator\Desktop\face\3.jpg',
            'C:\Users\Administrator\Desktop\face\4.jpg',
            'C:\Users\Administrator\Desktop\face\5.jpg',
        );
        echo '<pre>';
        foreach($arr as $item) {
            $this->load->library('aliapi');

            var_export($this->aliapi->detect_face($item)); 
        }

        // $this->load->library('aliapi');
        // $ret = $this->aliapi->detect_face($a);
        // var_export($ret);exit;
    }

    // 保存班主寄语操作
    public function save_teacher_content() {
        $userId = $this->post('user_id');
        $content = trim($this->post("content", false));
        // \n转换为<p>
        $arr = explode("\n", $content);
        $newStr = '';
        if($arr) {
            foreach($arr as $v) {
                $newStr .= '<p>' . $v . '</p>';
            }
        }
        // 入库
        $data = array(
            'content' => $newStr,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $userId);
        $this->db->update(SchoolModel::$schoolUserTable, $data);
        exit(json('修改成功', true));
    }

    /*
     * 班级文化页面
    */
    public function center_class_culture() {

        $this->htmlTitle = '班级文化';
        
        // 获取任课班级列表
        if($this->bindUserType == BIND_TYPE_TEACHER) {
             // 获取班主任对应的班级列表
             $coachParams['teacherId'] = $this->user['id'];
             $coachParams['coachType'] = COACH_TYPE_MASTER; 
             $this->load->model('staffModel');
             $coachList = $this->staffModel->get_coach_list($coachParams);
             $isMaster = false;
             $brandInfo = array();
             if($coachList) {
                 $masterClassIdArr = array();
                 // 获取任教班主任班级列表
                 foreach($coachList as $coach) {
                    $idArr = explode(',', $coach['class_ids']);
                    foreach($idArr as $id) {
                       if(!in_array($id, $masterClassIdArr)) {
                           array_push($masterClassIdArr, $id);
                       }
                    }
                }
                // 判断是否已删除
                foreach($masterClassIdArr as $masterClassId) {
                    $classInfo = $this->classesModel->get_class_info($masterClassId);
                    // 过滤年级已删除
                    if($classInfo) {
                        $gradeId = $classInfo['grade_id'];
                        $gradeInfo = $this->classesModel->get_grade_info($gradeId);
                    }
                    if($classInfo && $classInfo['is_delete'] == 0 && isset($gradeInfo) && $gradeInfo['is_delete'] == 0) {
                        $isMaster = true;
                        // 判断班主任对应的班级是否存在班牌
                        $brandInfo = $this->classesModel->get_brand_info_by_class($classInfo['id']);

                        // 班级简介<p>转换为\n
                        $classInfo['class_content'] = urldecode($classInfo['class_content']);
                        // var_export($classInfo['class_content']);exit;
                        $order = array("\r\n", "\n", "\r", "<p>");
                        $replace = '\n';
                        if($classInfo['class_content']) {
                            $classInfo['class_content'] = str_replace($order, $replace, $classInfo['class_content']);
                        }
                        if($classInfo['class_slogan']) {
                            $classInfo['class_slogan'] = str_replace($order, $replace, $classInfo['class_slogan']);
                        }
                        if($classInfo['class_word']) {
                            $classInfo['class_word'] = str_replace($order, $replace, $classInfo['class_word']);
                        }
                        break;
                    }
                }
             }

             // 管理员可以上传全校学生人脸
             if($this->user['user_type'] == USER_TYPE_SCHOOL) {
                 $isMaster = true;
             }

             // 班级寄语<p>转换为\n
             if($this->user['content']) {
                  $order = array("\r\n", "\n", "\r", "<p>");
                  $replace = '\n';
                  $this->user['content']=str_replace($order, $replace, $this->user['content']);
             }
             $this->isMaster = $isMaster;
             $this->brandInfo = $brandInfo;
             $this->classInfo = $classInfo;
        }

        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/center_class_culture');
    }

    // 保存班级简介操作
    public function save_class_content() {
        $classId = $this->post('class_id');
        $content = trim($this->post("class_content", false));
        // \n转换为<p>
        $arr = explode("\n", $content);
        $newStr = '';
        if($arr) {
            foreach($arr as $v) {
                $newStr .= '<p>' . $v . '</p>';
            }
        }
        // var_export($newStr);exit;
        $classContent = urlencode($newStr);
        // 入库
        $data = array(
            'class_content' => $classContent,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $classId);
        $this->db->update(ClassesModel::$classTable, $data);
        exit(json('修改成功', true));
    }
    // 保存班级格言操作
    public function save_class_slogan() {
        $classId = $this->post('class_id');
        $slogan = trim($this->post('class_slogan'));
        // 入库
        $data = array(
            'class_slogan' => $slogan,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $classId);
        $this->db->update(ClassesModel::$classTable, $data);
        exit(json('修改成功', true));
    }
    // 保存班级口号操作
    public function save_class_word() {
        $classId = $this->post('class_id');
        $word = trim($this->post('class_word'));
        // 入库
        $data = array(
            'class_word' => $word,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $classId);
        $this->db->update(ClassesModel::$classTable, $data);
        exit(json('修改成功', true));
    }

    /*
     * 扫码签到
    */
    // public function scan_sign() {
    //     $this->load->model('classesModel');
    //     $this->htmlTitle = '扫码签到';
    //     $courseId = $this->get('course_id');
    //     $brandId = $this->get('brand_id') ? $this->get('brand_id') : 0;
    //     $isSupplement = $this->get('is_supplement');
    //     $scheduleLesson = $this->classesModel->get_sch_lesson($courseId);
    //     // echo '<pre>';var_export($this->user);exit;
    //     if(empty($scheduleLesson)) {
    //         throw new Exception('课程不存在，请联系管理员');
    //     }
    //     $classInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
    //     $teachingClassIdArr = explode(',', $this->user['teaching_class_id']);
    //     // 无需签到
    //     if($classInfo['id'] != $this->user['class_id'] && !in_array($classInfo['id'], $teachingClassIdArr)) {
    //         throw new Exception('您不在本课程上课！');
    //     }

    //     // 获取学生当天最后一次签到
    //     $signData = $this->dataModel->get_student_sign_data(date("Y-m-d", time()), $this->user['id'], '', USER_TYPE_STUDENT);
    //     if($signData['course_id'] == $scheduleLesson['id']) {
    //         throw new Exception('无需重复签到！');
    //     }

    //     // echo '<pre>';var_export($this->user);exit;
    //     $islate = 0;
    //     if($classInfo['class_type'] == CLASSES_TYPE_NORMAL) {
    //         if($isSupplement) {
    //             // 补签
    //             $state = SIGN_STATE_NORMAL_SUPPLEMENT;
    //         } else {
    //             $state = SIGN_STATE_NORMAL;
    //         }
    //     } else {
    //         // 教学班
    //         if($isSupplement) {
    //             // 补签
    //             $state = SIGN_STATE_TEACH_SUPPLEMENT;
    //         } else {
    //             $state = SIGN_STATE_TEACH;
    //         }
    //     }

    //     // 插入签到记录
    //     // 入库，做个毛线逻辑
    //     $insert['school_id'] = $classInfo['school_id'];
    //     $insert['class_id'] = $classInfo['id'];
    //     $insert['course_id'] = $courseId;
    //     $insert['student_id'] = $this->user['id'];
    //     $insert['student_card_number'] = '';
    //     $insert['brand_id'] = $brandId;
    //     $insert['sign_type'] = SIGN_TYPE_SCAN;
    //     $insert['state'] = $state;
    //     $insert['sign_img'] = '';
    //     $insert['sign_date'] = date("Y-m-d", time());
    //     $insert['createtime'] = date("Y-m-d H:i:s", time());
    //     $insert['user_type'] = USER_TYPE_STUDENT;
    //     // 是否补签
    //     $insert['is_supplement'] = $isSupplement;
    //     // 是否重新签到
    //     $insert['is_refresh_sign'] = 1;
    //     // 第几节
    //     $insert['schedule_class_index'] = $scheduleLesson['schedule_class_index'];
    //     $this->db->insert(ClassesModel::$signTable, $insert);
    //     $signId = $this->db->insert_id();
    //     // 插入考勤临时表
    //     $this->db->insert(ClassesModel::$signTempTable, $insert);   
        
    //     // 发送模板消息
    //     $url = wx_url('pub/student_sign_detail/' . $signId);
    //     $data = array(
    //         'first' => array(
    //             'value' => '您好，' . $this->user['realname'] . '同学已完成签到：'
    //         ),
    //         'keyword1' => array(
    //             'value' => $this->user['class']['class_name']
    //         ),
    //         'keyword2' => array(
    //             'value' => date("Y-m-d H:i:s", strtotime($insert['createtime']))
    //         ),
    //         'keyword3' => array(
    //             'value' => $this->user['realname']
    //         )
    //     );
    //     $this->load->library('wxtemplate');
    //     // 重新签到才发送模板消息
    //     $this->wxtemplate->send_template_msg_for_user($this->user['id'], BIND_TYPE_STUDENT, WX_TEMPLATE_SCHEDULE, $data, $url);

    //     // 发送socket通知班牌
    //     $this->classesModel->send_school_brand_socket($classInfo['school_id'], CONTENT_TYPE_ALERT_SIGN_STUDENT, $this->user['id'], $brandId);

    //     exit(json('签到成功', true));
    // }

    // 扫码成功通知班牌
    public function scan_sign() {
        $brandId = $this->get('brand_id');
        // 发送socket通知班牌
        $this->classesModel->send_school_brand_socket($this->user['school_id'], CONTENT_TYPE_SCAN, $this->user['id'], $brandId);
        exit(json('', true));
    }

    // 班干信息页面
    public function class_leader() {
        $this->htmlTitle = '班干信息';
        
        // 只获取行政班
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
    
        // 管理员可以上传全校学生人脸

        // 获取班主任对应的班级列表
        $coachParams['teacherId'] = $this->user['id'];
        $coachParams['coachType'] = COACH_TYPE_MASTER; 
        $this->load->model('staffModel');
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $studentList = array();
        if($coachList) {
            $masterClassIdArr = array();
            // 获取任教班主任班级列表
            foreach($coachList as $coach) {
            $idArr = explode(',', $coach['class_ids']);
            foreach($idArr as $id) {
                if(!in_array($id, $masterClassIdArr)) {
                    array_push($masterClassIdArr, $id);
                }
            }
            }
            $classParams['isDelete'] = 0;
            $classParams['classId'] = implode(',', $masterClassIdArr);
            $classArr = $this->classesModel->get_class_list($classParams);
            if($classArr) {
                $class = $classArr[0];
                // 获取某班级所有学生
                $stuParams['schoolId'] = $this->user['school_id'];
                $stuParams['classId'] = $class['id'];
                $stuParams['isDelete'] = 0;
                $studentList = $this->schoolModel->get_student_list($stuParams);
                if($studentList) {
                    $hasJobList = array();
                    $notHasJobList = array();
                    foreach($studentList as $student) {
                        // 获取学生头像
                        $defaultHeadimg = $this->staticWxUrl . 'assets/img/head.png';
                        $student['face_image'] = $student['face_image'] ? $student['face_image'] . '!small' : $defaultHeadimg;
                        // 获取首字母
                        $student['realnameFirstChar'] = getFirstChar($student['realname']);
                        if($student['job']) {
                            array_push($hasJobList, $student);
                        } else {
                            array_push($notHasJobList, $student);
                        }
                    }
                    if($notHasJobList) {
                        // 按姓名首字母排序
                        $timeKey =  array_column($notHasJobList, 'realnameFirstChar');
                        array_multisort($timeKey, SORT_ASC, $notHasJobList);
                    }
                    // 有职务的放到前面
                    $studentArr = array_merge($hasJobList, $notHasJobList);
                    
                }
            }
        }
                    // echo'<pre>';var_export(count($studentArr));exit;
        $this->studentList = $studentArr;
        
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/class_leader');
    }
    // 保存学生职务操作
    public function save_student_job() {
        $id = $this->post('id');
        $job = trim($this->post('job'));
        // 入库
        $data = array(
            'job' => $job
        );
        $this->db->where('id', $id);
        $this->db->update(SchoolModel::$schoolStudentTable, $data);
        exit(json('修改成功', true));
    }
    // 班级之星页面
    public function class_star() {
        $this->htmlTitle = '班级之星';
        
        // 只获取行政班
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
    
        // 管理员可以上传全校学生人脸

        // 获取班主任对应的班级列表
        $coachParams['teacherId'] = $this->user['id'];
        $coachParams['coachType'] = COACH_TYPE_MASTER; 
        $this->load->model('staffModel');
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $studentList = array();
        $classId = 0;
        if($coachList) {
            $masterClassIdArr = array();
            // 获取任教班主任班级列表
            foreach($coachList as $coach) {
            $idArr = explode(',', $coach['class_ids']);
            foreach($idArr as $id) {
                if(!in_array($id, $masterClassIdArr)) {
                    array_push($masterClassIdArr, $id);
                }
            }
            }
            $classParams['isDelete'] = 0;
            $classParams['classId'] = implode(',', $masterClassIdArr);
            $classArr = $this->classesModel->get_class_list($classParams);
            if($classArr) {
                $class = $classArr[0];
                $classId = $class['id'];
                // 获取某班级所有学生
                $stuParams['schoolId'] = $this->user['school_id'];
                $stuParams['classId'] = $class['id'];
                $stuParams['isDelete'] = 0;
                $studentList = $this->schoolModel->get_student_list($stuParams);
                if($studentList) {
                    $hasStarList = array();
                    $notHasStarList = array();
                    foreach($studentList as $student) {
                        // 获取学生头像
                        $defaultHeadimg = $this->staticWxUrl . 'assets/img/head.png';
                        $student['face_image'] = $student['face_image'] ? $student['face_image'] . '!small' : $defaultHeadimg;
                        // 获取首字母
                        $student['realnameFirstChar'] = getFirstChar($student['realname']);
                        if($student['id'] == $class['class_star']) {
                            $student['is_star'] = true;
                            array_push($hasStarList, $student);
                        } else {
                            $student['is_star'] = false;
                            array_push($notHasStarList, $student);
                        }
                    }
                    if($notHasStarList) {
                        // 按姓名首字母排序
                        $timeKey =  array_column($notHasStarList, 'realnameFirstChar');
                        array_multisort($timeKey, SORT_ASC, $notHasStarList);
                    }
                    // 有职务的放到前面
                    $studentArr = array_merge($hasStarList, $notHasStarList);
                }
            }
        }
        // echo'<pre>';var_export($hasStarList);exit;
        $this->studentList = $studentArr;
        $this->classId = $classId;
        $this->display(WX_DIR . DIRECTORY_SEPARATOR . 'user/class_star');
    }
    // 保存学生职务操作
    public function save_class_star() {
        $classId = $this->post('class_id');
        $studentId = $this->post('student_id');
        $isCancel = $this->post('is_cancel');
        // 取消
        if($isCancel) {
            $studentId = 0;
        }
        // 入库
        $data = array(
            'class_star' => $studentId
        );
        $this->db->where('id', $classId);
        $this->db->update(ClassesModel::$classTable, $data);
        exit(json('修改成功', true));
    }
}